﻿using IOP.ISEA;
using IOP.SgrA;
using IOP.SgrA.ECS;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using Silk.NET.Vulkan;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace VkSmaple93
{
    [ModulePriority(ModulePriority.Assets)]
    public class AssetsModule : VulkanModule, IVulkanRenderWapperModule
    {
        private readonly ILogger<AssetsModule> _Logger;

        public AssetsModule(ILogger<AssetsModule> logger)
        {
            _Logger = logger;
        }

        public VulkanRenderWapper RenderWapper { get; set; }

        protected override async Task Load(VulkanGraphicsManager graphicsManager)
        {
            try
            {
                var basePath = AppContext.BaseDirectory;
                var modelsPath = Path.Combine(basePath, "Assets", "Models");
                var texPath = Path.Combine(basePath, "Assets", "Textures");
                var lDevice = graphicsManager.VulkanDevice;

                ISEADocument document = new ISEADocument();
                await document.Load(Path.Combine(AppContext.BaseDirectory, "test93.isea"));
                var renders = await graphicsManager.CreateRenderObjectsFromISEA<RenderObject>(document);
                var land = renders.Where(x => x.Name == "Land").First();
                var landTex = land.GetComponent<VulkanTexture>("LandTex");
                var landMapData = landTex.TextureData as BntexVulkanTextureData;

                graphicsManager.TryGetRenderGroup("Land", out IRenderGroup group);

                var landData = new LandData();
                float[] data = landData.GenData((int)landMapData.Width, (int)landMapData.Height);
                var landMesh = graphicsManager.CreateEmptyMesh<VRO>("LandMesh")
                    .CreateVecticesBuffer(data, landData.VCount, lDevice, SharingMode.Exclusive);
                land.AddComponent(landMesh);

                var archetype = ContextManager.CreateArchetype(new TransformComponent());
                ContextManager.CreateContexts(1, archetype, group, land);
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message + "\r\n" + e.StackTrace);
            }
        }

        protected override Task Unload(VulkanGraphicsManager manager)
        {
            return Task.CompletedTask;
        }
    }
}
